package main;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;

public class ReflectionFields {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		String classPath = "com.model.Student";
		
		Class<?> reflectionClass = null;
		
		try {
			reflectionClass = Class.forName(classPath);
		} catch (ClassNotFoundException e) {
			System.out.println("Class not found!!!");
			e.printStackTrace();
		}
		
		//1. GET ALL FIELDS
		
		Field[] fields = reflectionClass.getDeclaredFields();
		
		for(Field field : fields){
			System.out.println(" Field name: " + field.getName() + " ; Type: " + field.getType() + " ; Public: " + Modifier.isPublic(field.getModifiers()));
		}
		
		
		// 2. GET & SET FIELD VALUE
		
		Constructor<?> constructor;
		Object student = null;
		
		try {
			constructor = reflectionClass.getDeclaredConstructor(String.class, String.class, int.class);
			constructor.setAccessible(true);
			
			student = constructor.newInstance("SV2", "Victor Vu", 20);
			
		} catch (NoSuchMethodException | SecurityException e1) {
			e1.printStackTrace();
		} catch (InstantiationException | IllegalAccessException
				| IllegalArgumentException | InvocationTargetException e) {
			e.printStackTrace();
		}
		
		
		Field field = null;
		
		try {
			field = reflectionClass.getDeclaredField("size");
		} catch (NoSuchFieldException | SecurityException e) {
			System.out.println("Can not find field!!!");
			e.printStackTrace();
		}
		
		try {
			// set value
			field.set(student, new Integer(100));
			
			//get value
			int valueField = field.getInt(student);
			System.out.println("Value of field: " + valueField);
			
		} catch (IllegalAccessException | IllegalArgumentException e) {
			e.printStackTrace();
		}
		
		
		// 3. PRIVATE FIELD
		try {
			field = reflectionClass.getDeclaredField("IdSV");
			field.setAccessible(true);
			
			field.set(student, "SV1000");
			
			String idSV = (String) field.get(student);
			
			System.out.println("Student id: " + idSV);
			
		} catch (NoSuchFieldException | SecurityException e) {
			System.out.println("Can not find field!!!");
			e.printStackTrace();
		} catch (IllegalArgumentException | IllegalAccessException e) {
			System.out.println("Can not operate on this field!!!");
			e.printStackTrace();
		}
		
	}

}
